package com.tjetc.common.handlers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.entity.Season;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SeasonTypeHandler extends BaseTypeHandler<Season> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Season parameter, JdbcType jdbcType) throws SQLException {
        try {
            // 将 Season 对象转换为 JSON 字符串并设置到 PreparedStatement
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (IOException e) {
            throw new SQLException("Error while serializing Season to JSON", e);
        }
    }

    @Override
    public Season getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {
            // 从数据库中获取 JSON 字符串并转换为 Season 对象
            String json = rs.getString(columnName);
            return json == null ? null : objectMapper.readValue(json, Season.class);
        } catch (IOException e) {
            throw new SQLException("Error while deserializing JSON to Season", e);
        }
    }

    @Override
    public Season getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            String json = rs.getString(columnIndex);
            return json == null ? null : objectMapper.readValue(json, Season.class);
        } catch (IOException e) {
            throw new SQLException("Error while deserializing JSON to Season", e);
        }
    }


    @Override
    public Season getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            String json = cs.getString(columnIndex);
            return json == null ? null : objectMapper.readValue(json, Season.class);
        } catch (IOException e) {
            throw new SQLException("Error while deserializing JSON to Season", e);
        }
    }
}
